package com.mtzqc.net.config

import android.os.Build
import android.os.SystemClock
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.mtzqc.helper.PrivacyHelper
import com.mtzqc.net.RxConfig
import rxhttp.wrapper.callback.Consumer
import rxhttp.wrapper.param.Param
import java.util.concurrent.atomic.AtomicInteger

class ParamAssembly : Consumer<Param<*>> {
    /**
     * 设备
     */
    private val device: String by lazy {
        "Android_${DeviceUtils.getUniqueDeviceId()}_${Build.VERSION.SDK_INT}_${DeviceUtils.getSDKVersionName()}_${Build.BRAND}_${DeviceUtils.getModel()}"
    }
    private val version: String by lazy {
        "${AppUtils.getAppVersionCode()}_${AppUtils.getAppVersionName()}"
    }

    /**
     * 同一次请求Id
     */
    private val launchTime = SystemClock.elapsedRealtime()

    /**
     * 请求计数器
     */
    private val counterRequest = AtomicInteger(0)


    override fun accept(param: Param<*>) {
        if (param.simpleUrl.startsWith(RxConfig.baseUrl)) {
            param.also {
                if (PrivacyHelper.isAgree()) {
                    it.addHeader(RxConfig.HEADER_DEVICE, device)
                }
                //添加token
                it.addHeader(RxConfig.HEADER_TOKEN, "")
            }
                .addHeader(RxConfig.HEADER_LAUNCH, launchTime.toString())
                .addHeader(RxConfig.HEADER_REQ, counterRequest.incrementAndGet().toString())
                .addHeader(RxConfig.HEADER_VERSION, version)
        }
    }
}